#region Usings
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
#endregion

namespace BK.Web.UI
{
	public class WindsorControllerFactory : DefaultControllerFactory
	{
		private readonly WindsorContainer _container;

		#region C'tors
		public WindsorControllerFactory()
		{
			_container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
			var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
			                      where typeof (IController).IsAssignableFrom(t)
			                      select t;
			foreach (Type controllerType in controllerTypes)
			{
				_container.AddComponentLifeStyle(controllerType.FullName, controllerType, LifestyleType.Transient);
			}
		}

		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			return (IController) _container.Resolve(controllerType);
		}
		#endregion
	}
}